package com.zx.zxapiorder.listener;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.rabbitmq.client.Channel;
import com.zx.zxapicommon.common.BaseResponse;
import com.zx.zxapicommon.constant.OrderConstant;
import com.zx.zxapicommon.model.vo.LockChargingVo;
import com.zx.zxapiorder.feign.UserFeignServices;
import com.zx.zxapiorder.model.entity.ApiOrder;
import com.zx.zxapiorder.model.entity.ApiOrderLock;
import com.zx.zxapiorder.service.ApiOrderLockService;
import com.zx.zxapiorder.service.ApiOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;

import static com.zx.zxapicommon.constant.RabbitmqConstant.*;

/**
 * 订单超时处理监听器
 *
 * @author 张旭
 * @version 1.0
 */
@Component
@Slf4j
public class OrderTimeOutListener {
    @Autowired
    private ApiOrderLockService apiOrderLockService;

    @Autowired
    private ApiOrderService apiOrderService;

    @Autowired
    private UserFeignServices userFeignServices;

    /**
     * 当订单不存在或者未支付，开始回滚
     * @param apiOrder
     * @param message
     * @param channel
     * @throws IOException
     */
    @Transactional(rollbackFor = Exception.class)
    @RabbitListener(queues = ORDER_TIMEOUT_QUEUE_NAME)
    public void delayListener(ApiOrder apiOrder, Message message, Channel channel) throws IOException {
        try {
            log.error("监听到死信队列消息==>{}", apiOrder);
            Long id = apiOrder.getId();
            ApiOrder order = apiOrderService.getById(id);

            //订单
            if (null == order) {
                //库存已经扣了，但是出现异常，未能够生成订单和锁定订单结果
                //回滚库存
                Long orderNum = apiOrder.getOrderNum();
                LockChargingVo lockChargingVo = new LockChargingVo();
                lockChargingVo.setOrderNum(orderNum);
                lockChargingVo.setInterfaceId(apiOrder.getInterfaceId());
                BaseResponse baseResponse = userFeignServices.unlockAvailablePieces(lockChargingVo);
                if (baseResponse.getCode() != 0) {
                    throw new RuntimeException();
                }
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            }

            //订单未支付
            Integer status = order.getStatus();
            if (status == 0) {
                Long orderNum = apiOrder.getOrderNum();
                //订单未完成
                String orderSn = order.getOrderSn();
                //更新库存状态信息表
                apiOrderLockService.update(new UpdateWrapper<ApiOrderLock>().eq("orderSn", orderSn).set("lockStatus", 0));
                //更新订单表状态
                apiOrderService.update(new UpdateWrapper<ApiOrder>().eq("id", apiOrder.getId()).set("status", 2));
                //远程调用 - 解锁库存
                LockChargingVo lockChargingVo = new LockChargingVo();
                lockChargingVo.setOrderNum(orderNum);
                lockChargingVo.setInterfaceId(apiOrder.getInterfaceId());
                BaseResponse baseResponse = userFeignServices.unlockAvailablePieces(lockChargingVo);
                if (baseResponse.getCode() != 0) {
                    throw new RuntimeException();
                }
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }
}

